package com.rub.android.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.rub.android.dto.JsonResult
import com.rub.android.service.UserService

/**
 * https://www.wanandroid.com/blog/show/2554
 */
class UserViewModel(repository: UserService) : ViewModel() {

    //请求参数
    private var requestData = MutableLiveData<RequestParam>()

    val responseData = Transformations.switchMap(requestData) {
        liveData {
            val result = try {
                val ret = repository.refreshLogin(it.userName, it.passWord)
                Result.success(ret)
            } catch (e: Exception) {
                Result.failure<JsonResult>(e)
            }
            emit(result)
        }
    }

    /**
     * 实现
     */
    fun login(userName: String,passWord: String) {
        requestData.value = RequestParam(userName,passWord)
    }

    /**
     * 内练类
     */
    inner class RequestParam(val userName: String, val passWord: String)

}